﻿using System;
using System.Text;
using System.Linq;
using Dapper;
using Dapper.Contrib.Extensions;

namespace EC.Application.Impl
{
    using EC.Application.Interface;

    using EC.Entity;
    using EC.Entity.Query;
    using EC.Entity.Request.Customer;
    using EC.Entity.Request.Token;
    using EC.Entity.Response.Customer;
    using EC.Entity.Response.PointsLog;
    using EC.Entity.Response.Token;
    using EC.Entity.Tables;
    using EC.Util;

    /// <summary>
    /// 会员接口实现
    /// </summary>
    public class CustomerServiceImpl: CustomerService
    {
        #region 注入
        /// <summary>
        /// 数据接口
        /// </summary>
        private readonly IDBSession _dbSession;

        /// <summary>
        /// 数据库上下文
        /// </summary>
        /// <param name="context">数据库上下文</param>
        public CustomerServiceImpl(IDBSession dbSession)
        {
            _dbSession = dbSession;
        }
        #endregion

        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns></returns>
        public CustomerResponse Get(int id)
        {
            var customerResponse = _dbSession.DbConnection.QueryFirst<CustomerResponse>("select * from customer where Id=@Id", new { Id = id });
            if (customerResponse != null)
            {
                return customerResponse;
            }

            return null;
        }

        /// <summary>
        /// 根据会员编号获取Token
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns></returns>
        public TokenResponse GetToken(int customerId)
        {

            var tokenResponse = _dbSession.DbConnection.Query<TokenResponse>("select * from token where CustomerId=@CustomerId", new { CustomerId = customerId });
            if (tokenResponse != null && tokenResponse.Any())
            {
                return tokenResponse.First();
            }
            return null;
        }

        /// <summary>
        /// Token新增、编辑
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public JResult SaveToken(SaveTokenRequest request)
        {
            var response = new JResult()
            {
                Success = false
            };

            try
            {
                var token = _dbSession.DbConnection.Query<Token>("select * from token where MerchantId=@MerchantId", new { MerchantId = request.MerchantId });
                if (token != null && token.Any())
                {
                    var model = token.First();
                    model.AppId = request.AppId;
                    model.AppSecret = request.AppSecret;
                    model.Status = request.Status;

                    //更新
                    _dbSession.DbConnection.Update<Token>(model);

                    response.Success = true;
                }
                else
                {
                    var model = new Token()
                    {
                        MerchantId = request.MerchantId,
                        AppId = request.AppId,
                        AppSecret = request.AppSecret,
                        Status = request.Status,
                    };

                    //新增
                    long resultId = _dbSession.DbConnection.Insert<Token>(model);

                    if (resultId <= 0)
                    {
                        throw new Exception("新增Token失败.");
                    }

                    response.Success = true;
                }
            }
            catch(Exception ex)
            {
                response.Message = ex.Message;
            }

            return response;
        }

        /// <summary>
        /// 状态
        /// </summary>
        /// <returns></returns>
        public JResult UpdateStatus(int id, sbyte status)
        {
            var response = new JResult()
            {
                Success = false
            };

            try
            {
                var customer = _dbSession.DbConnection.QueryFirst<Token>("select * from customer where Id=@Id", new { CustomerId = id });
                if (customer == null)
                {
                    throw new Exception("会员记录不存在.");
                }

                var updateSql = "UPDATE customer SET Status=@Status WHERE Id=@Id";

                int result = _dbSession.DbConnection.Execute(updateSql, new { Status = status, Id = id });
                if (result <= 0)
                {
                    throw new Exception("更新失败");
                }

                response.Success = true;
                response.Message = "操作成功.";
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
            }
            return response;
        }

        /// <summary>
        /// 重置密码
        /// </summary>
        /// <returns></returns>
        public JResult SaveResetPassWord(ResetPassWordRequest request)
        {
            var response = new JResult()
            {
                Success = false
            };

            try
            {
                var customer = _dbSession.DbConnection.QueryFirst<Customer>("select * from customer where Id=@CustomerId", new { CustomerId = request.CustomerId });
                if (customer == null)
                {
                    throw new Exception("会员记录不存在.");
                }

                var updateSql = "UPDATE customer SET PassWord=@PassWord WHERE Id=@Id";

                int result = _dbSession.DbConnection.Execute(updateSql, new { PassWord = EncryptionUtil.EncryptWithMd5(request.NewPassword), Id = customer.Id });
                if (result <= 0)
                {
                    throw new Exception("更新失败");
                }

                response.Success = true;
                response.Message = "操作成功.";
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
            }
            return response;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public PagedList<CustomerQueryResponse> GetPager(CustomerQuery query)
        {
            var currentPageIndex = 0;

            if (query.CurrentPageIndex.Value > 0)
            {
                currentPageIndex = (query.CurrentPageIndex.Value - 1) * query.PageSize.Value;
            }

            var files = "Id,Account,Name,Points,Email,Status,LoginCount,CreatedDate";
            var tableName = "customer";
            var orderby = "ORDER BY Id DESC";
            var where = "where 1=1";

            #region 条件
            if (!string.IsNullOrEmpty(query.Account))
            {
                where += string.Format(" And Account like'%{0}%'", query.Account);
            }
            #endregion

            var sb = new StringBuilder();

            sb.AppendFormat("SELECT COUNT(1) FROM {0} {1};", tableName, where);
            sb.AppendFormat("SELECT {0} FROM {1} {2} {3} LIMIT {4},{5};", files, tableName, where, orderby, currentPageIndex, query.PageSize.Value);

            using (var multi = _dbSession.DbConnection.QueryMultiple(sb.ToString()))
            {
                var count = multi.ReadFirst<int>();

                var list = multi.Read<CustomerQueryResponse>();

                return new PagedList<CustomerQueryResponse>()
                {
                    TData = list,
                    CurrentPageIndex = query.CurrentPageIndex.Value,
                    TotalCount = count
                };
            }

        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public PagedList<PointsLogQueryResponse> GetPointsLogPager(PointsLogQuery query)
        {
            var currentPageIndex = 0;

            if (query.CurrentPageIndex.Value > 0)
            {
                currentPageIndex = (query.CurrentPageIndex.Value - 1) * query.PageSize.Value;
            }

            var files = "Id,Type,Points,LastPoints,Remark,CreatedDate";
            var tableName = "pointslog";
            var orderby = "ORDER BY Id DESC";
            var where = string.Format("where CustomerId={0}", query.CustomerId);

            var sb = new StringBuilder();

            sb.AppendFormat("SELECT COUNT(1) FROM {0} {1};", tableName, where);
            sb.AppendFormat("SELECT {0} FROM {1} {2} {3} LIMIT {4},{5};", files, tableName, where, orderby, currentPageIndex, query.PageSize.Value);

            using (var multi = _dbSession.DbConnection.QueryMultiple(sb.ToString()))
            {
                var count = multi.ReadFirst<int>();

                var list = multi.Read<PointsLogQueryResponse>();

                return new PagedList<PointsLogQueryResponse>()
                {
                    TData = list,
                    CurrentPageIndex = query.CurrentPageIndex.Value,
                    TotalCount = count
                };
            }
        }
    }
}
